package cn.io0288.ks;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import cn.io0288.ks.Adapter.ContactsBeanAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = "Debug";
    private static final String REDIS_ROOT = "ks_txl:";
    private static final int PERMISS_CONTACT = 1;
    private static final String[] PERMISS_LIST = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.INTERNET};
    private final ContactUtils contactUtils = new ContactUtils();
    private String[] mpermissList = {};
    private String uid;

    private Button btn_down = null;
    private Button btn_up = null;
    private Button btn_set = null;
    private TextView tv_c_count = null;
    private RecyclerView mRecyclerView = null;
    private EditText et_uid = null;
    private FloatingActionButton btn_fab = null;
    private ContactsBeanAdapter adapter;

    /**
     * 初始化
     */
    private void init() {
        mpermissList = PERMISS_LIST;
        btn_down = findViewById(R.id.btn_down);
        btn_up = findViewById(R.id.btn_up);
        btn_set = findViewById(R.id.btn_set);
        tv_c_count = findViewById(R.id.c_count);
        tv_c_count.setText(getString(R.string.c_count, 0, 0, 0));
        mRecyclerView = findViewById(R.id.lv);
        et_uid = findViewById(R.id.et_uid);
        btn_fab = findViewById(R.id.fab);

        btn_fab.setOnClickListener(v -> {
            addPermissByPermissionList(MainActivity.this, PERMISS_LIST, PERMISS_CONTACT);
            showContacts();
        });

        btn_up.setOnClickListener(view -> {
            String baseUrl = "https://api.ali.io0288.cn/redis/index.php";
            uid = et_uid.getText().toString().trim();
            if (contactUtils.tempContactsList == null) {
                hint(view.getContext(), "没有联系人");
                hint(view.getContext(), new Gson().toJson(contactUtils.tempContactsList));
                return;
            }
            String contacts_json = new Gson().toJson(contactUtils.tempContactsList);
            Log.i(LOG_TAG, "contacts_json: \n" + contacts_json);

            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("method", "set")
                    .add("key", REDIS_ROOT + uid)
                    .add("value", contacts_json)
                    .add("time", "-2").build();
            // 构建请求
            Request request = new Request.Builder().url(baseUrl).post(formBody).build();
            // 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(LOG_TAG, "请求错误: " + baseUrl);
                    throw new RuntimeException(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response)
                        throws IOException {
                    if (response.isSuccessful()) {
                        // 请求成功，处理响应
                        String responseData = null;
                        if (response.body() != null) {
                            responseData = response.body().string();
                        }
                        // 打印响应数据
                        Log.i(LOG_TAG, responseData);
                        runOnUiThread(() -> hint(view.getContext(), "上传成功"));
                    } else {
                        // 处理错误响应
                        Log.e(LOG_TAG, "请求失败: " + baseUrl);
                        Log.e(LOG_TAG, "错误代码: " + response.code());
                        runOnUiThread(() -> hint(view.getContext(), "上传失败"));
                    }
                }
            });
        });

        btn_set.setOnClickListener(view -> {
            for (ContactsBean c : contactUtils.newContactsList)
                ContactUtils.addContacts(view.getContext(), c);
            hint(view.getContext(), "写入完成");
            // 置空
            contactUtils.newContactsList = new ArrayList<>();
        });

        btn_down.setOnClickListener(view -> {
            String baseUrl = "https://api.ali.io0288.cn/redis/index.php";
            uid = et_uid.getText().toString().trim();

            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("method", "get")
                    .add("key", REDIS_ROOT + uid).build();
            // 构建请求
            Request request = new Request.Builder().url(baseUrl).post(formBody).build();
            // Async 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(LOG_TAG, "请求错误: " + baseUrl);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        // 请求成功，处理响应
                        String responseData = response.body().string();
                        // 打印响应数据
                        Log.i(LOG_TAG, "返回数据：" + responseData);
                        runOnUiThread(() -> hint(view.getContext(), "下载成功"));

                        Type listType = new TypeToken<ArrayList<ContactsBean>>() {
                        }.getType();
                        // 数据不存在时返回空
                        if (responseData.equals("404"))
                            contactUtils.remoteContactsList = new ArrayList<>();
                        else
                            contactUtils.remoteContactsList = new Gson().fromJson(responseData, listType);
                        Log.i(LOG_TAG, "远程通讯录大小：" + contactUtils.remoteContactsList.size());

                        runOnUiThread(() -> {
                            addPermissByPermissionList(MainActivity.this, PERMISS_LIST, PERMISS_CONTACT);
                            showContacts();
                        });
                    } else {
                        // 处理错误响应
                        Log.e(LOG_TAG, "请求失败: " + baseUrl);
                        Log.e(LOG_TAG, "错误代码: " + response.code());
                        runOnUiThread(() -> hint(view.getContext(), "下载失败"));
                    }
                }
            });
        });

        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this,
                        new RecyclerItemClickListener.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Log.d(LOG_TAG, "onItemClick : postion " + position);
                                ContactsBean c = adapter.getItem(position);
                                hint(view.getContext(), c.name+", "+c.phone[0]);
                                callPhone(c.phone[0]);
                            }

                            @Override
                            public void onLongClick(View view, int position) {
                                Log.d(LOG_TAG, "onLongClick position : " + position);
                                Log.i(LOG_TAG, adapter.getItem(position).lookupKey);

                                // onItemClick(view, posotion);
                            }
                        }
                )
        );
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        init();
    }

    /**
     * 获取联系人
     */
    private void showContacts() {
        // 缺失权限检查
        if (mpermissList != null) {
            hint(MainActivity.this, "权限缺失");
            dealwithPermiss(MainActivity.this, mpermissList[0]);
            return;
        }
        // 获取本地通讯录
        contactUtils.localContactsList = ContactUtils.getAllContacts(MainActivity.this);
        // 初始化去重与新增缓存
        contactUtils.tempContactsList = new ArrayList<>();
        contactUtils.newContactsList = new ArrayList<>();

        if (contactUtils.remoteContactsList == null)
            contactUtils.remoteContactsList = new ArrayList<>();
        if (contactUtils.localContactsList.isEmpty())
            hint(MainActivity.this, "通讯录空空如也~");
        Log.i(LOG_TAG, "localContactsList.size " + contactUtils.localContactsList.size());
        Log.i(LOG_TAG, "localContactsList " + contactUtils.localContactsList.toString());

        // 加载本地
        contactUtils.tempContactsList.addAll(contactUtils.localContactsList);
        // 远程是否存在
        if (contactUtils.remoteContactsList.isEmpty()) {
            Log.i(LOG_TAG, "remoteContactsList 不存在");
        } else {
            Log.i(LOG_TAG, "remoteContactsList.size " + contactUtils.remoteContactsList.size());
            Log.i(LOG_TAG, "remoteContactsList " + contactUtils.remoteContactsList.toString());
        }

        //联系人去重, 远程不为空
        if (!contactUtils.remoteContactsList.isEmpty()) {
            Set<String> set = new HashSet<>();
            // 加入已有联系人名称
            Log.i(LOG_TAG, "localContactsList： " + contactUtils.localContactsList.size());
            // 本地非空, 加入集合
            if (!contactUtils.localContactsList.isEmpty())
                for (ContactsBean c : contactUtils.localContactsList)
                    set.add(c.name);
            //以远程名称为参照加入集合去重
            for (ContactsBean c : contactUtils.remoteContactsList) {
                c.setTag(ContactsBean.TAG_REMOTE);
                if (set.add(c.name)) {
                    c.setLookupKey("");
                    contactUtils.newContactsList.add(c);
                }
            }
            contactUtils.tempContactsList.addAll(contactUtils.newContactsList);
            Log.i(LOG_TAG, "去重结果： " + contactUtils.tempContactsList.size());
        } else {
            contactUtils.tempContactsList = contactUtils.localContactsList;
        }

        Collections.sort(contactUtils.tempContactsList);
        adapter = new ContactsBeanAdapter(MainActivity.this, contactUtils.tempContactsList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(adapter);
        tv_c_count.setText(getString(R.string.c_count, contactUtils.localContactsList.size(), contactUtils.tempContactsList.size(), contactUtils.remoteContactsList.size()));
    }

    /**
     * 动态请求权限
     */
    public void addPermissByPermissionList(Activity activity, String[] permissList, int request) {
        // 检查权限是否缺失
        mpermissList = null;
        ArrayList<String> mPermissionList = new ArrayList<>();
        for (String s : permissList) {
            if (ContextCompat.checkSelfPermission(activity, s)
                    != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(s);
            }
        }
        // 判断结果
        if (mPermissionList.isEmpty()) {  //权限均已授权
            hint(MainActivity.this, "权限获取成功");
        } else {
            //请求权限方法
            mpermissList = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(activity, mpermissList, request); //这个触发下面onRequestPermissionsResult这个回调
        }
    }

    /**
     * requestPermissions的回调
     * 请求权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllGranted = true;
        //判断是否拒绝 拒绝后处理，取消再次提示的处理
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                hasAllGranted = false;
                break;
            }
        }
        if (hasAllGranted) { //同意权限做的处理,开启服务提交通讯录
            showContacts();
            Toast.makeText(this, "同意授权", Toast.LENGTH_SHORT).show();
        } else {
            //拒绝授权做的处理，弹出弹框提示用户授权
            dealwithPermiss(MainActivity.this, permissions[0]);
        }

    }

    /**
     * 权限缺失提示
     */
    public void dealwithPermiss(final Activity context, String permission) {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("权限缺失").setMessage("程序运行缺少必要的系统权限，请在设置中允许。")
                    .setPositiveButton("设置", (dialog, which) -> {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", context.getApplicationContext().getPackageName(), null);
                        intent.setData(uri);
                        context.startActivity(intent);
                    })
                    .setNegativeButton("关闭", (dialog, which) -> {
                        Toast.makeText(MainActivity.this, "取消操作", Toast.LENGTH_SHORT).show();

                        finishAffinity();
                        System.exit(0);
                    }).show();
        }
    }

    /**
     * Toast提示
     */
    private void hint(Context c, String str) {
        Toast.makeText(c, str, Toast.LENGTH_SHORT).show();
        Log.i(LOG_TAG, str);
    }

    /**
     * CALL_PHONEb拨打电话
     */
    private void callPhone(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL); // 使用 ACTION_DIAL 进行拨号
        intent.setData(Uri.parse("tel:" + phoneNumber)); // 设置电话号码
        startActivity(intent); // 启动拨号界面
    }
}